<?php
class ContactIndexController  extends Zone_Action{
	protected function fieldCompany(){
		return array(
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),
			date_updated	=> array(
				type			=> 'NONE',
				default_value	=> new Model_Expr('NOW()')
			),
			title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Tên giao dịch'
			),
			email => array(
				type 		=> 'EMAIL',
				form_label  => 'email'
			),
			desc => array(
				type 		=> 'CHAR',
				form_label  => 'Ghi chú'
			),
			phone => array(
				type => 'CHAR',
				form_label => 'Phone'
			),
			mobile => array(
				type => 'CHAR',
				form_label => 'Mobile'
			),
			fax => array(
				type => 'CHAR',
				form_label => 'Fax'
			),
			address => array(
				type => 'CHAR',
				form_label => 'Địa chỉ'
			),
			address2 => array(
				type => 'CHAR',
				form_label => 'Địa chỉ phụ'
			),
			homepage => array(
				type => 'CHAR',
				form_label => 'Trang web'
			)
		);
	}

	protected function fieldPerson(){
		return array(
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),
			date_updated	=> array(
				type			=> 'NONE',
				default_value	=> new Model_Expr('NOW()')
			),
			title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Tên'
			),
			job_title => array(
				type => 'CHAR',
				form_label => 'Chức vụ'
			),
			company_id => array(
				type => 'INT',
				form_label => 'Công ty'
			),
			department => array(
				type => 'CHAR',
				form_label => 'Phòng ban'
			),
			email => array(
				type 		=> 'EMAIL',
				form_label  => 'email'
			),
			phone => array(
				type => 'CHAR',
				form_label => 'Phone'
			),
			mobile => array(
				type => 'CHAR',
				form_label => 'Mobile'
			),
			fax => array(
				type => 'CHAR',
				form_label => 'Fax'
			),
			address => array(
				type => 'CHAR',
				form_label => 'Địa chỉ'
			),
			address2 => array(
				type => 'CHAR',
				form_label => 'Địa chỉ phụ'
			),
			homepage => array(
				type => 'CHAR',
				form_label => 'Trang web'
			)
		);
	}

	/* menu */
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `date_created` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','email','fax','phone','address','mobile');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$labels = $this->Model->fetchAll("SELECT * FROM `contact_labels` WHERE `user_id`='$user_id'");
		$this->set(array(
			labels	=> $labels
		));
		
		//label
		if( get('label_id',0) ){
			$vars['label_id'] = get('label_id');
			$where1 = " AND EXISTS( SELECT `t`.`contact_id` FROM `contacts_contact_labels` as `t` 
				WHERE `t`.`contact_id`=`a`.`ID` AND `t`.`label_id`='".get('label_id')."' AND `t`.`type`='person' ) ";

			$where2 = " AND EXISTS( SELECT `t`.`contact_id` FROM `contacts_contact_labels` as `t` 
				WHERE `t`.`contact_id`=`b`.`ID` AND `t`.`label_id`='".get('label_id')."' AND `t`.`type`='company' ) ";
		}
		
		$type = get('type','all');
		
		if(  $type == 'person' ){
		
			$vars['type'] = 'person';
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
				FROM  `contacts` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id'
						$where1
			");
					
			$posts = $this->Model->fetchAll("SELECT	
					`a`.`ID`,
					`a`.`title`,
					`a`.`email`,
					`a`.`fax`,
					`a`.`phone`,
					`a`.`address`,
					'person' as `type`,
					`a`.`date_created`,
					`a`.`date_updated`,
					`a`.`created_by_id`
				FROM  `contacts` as `a`
				WHERE
					`a`.`is_draft`='no'
					AND `a`.`created_by_id`='$user_id'
					$where1
			$order_by $limit");		
			
		}else if( $type == 'company'){
			
			$vars['type'] = 'company';
		
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
				FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id'
						$where2
			");
					
			$posts = $this->Model->fetchAll("SELECT	
					`b`.`ID`,
					`b`.`title`,
					`b`.`email`,
					`b`.`fax`,
					`b`.`phone`,
					`b`.`address`,
					'company' as `type`,
					`b`.`date_created`,
					`b`.`date_updated`,
					`b`.`created_by_id`
				FROM  `contacts_companies` as `b`
				WHERE
					`b`.`is_draft`='no'
					AND `b`.`created_by_id`='$user_id'
					$where2
			$order_by $limit");
			
		}else{
			$total = $this->Model->fetchOne("SELECT COUNT(*) FROM ( ( SELECT	
						`a`.`ID`
					FROM  `contacts` as `a`
					WHERE
						`a`.`is_draft`='no'
						AND `a`.`created_by_id`='$user_id'
						$where1
				) UNION 
				( SELECT
						`b`.`ID`
					FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id'
						$where2
				)) as `k`
			");
					
			$posts = $this->Model->fetchAll(" 
				( SELECT	
						`a`.`ID`,
						`a`.`title`,
						`a`.`email`,
						`a`.`fax`,
						`a`.`phone`,
						`a`.`address`,
						'person' as `type`,
						`a`.`date_created`,
						`a`.`date_updated`,
						`a`.`created_by_id`
					FROM  `contacts` as `a`
					WHERE
						`a`.`is_draft`='no'
						AND `a`.`created_by_id`='$user_id'
						$where1
				) UNION 
				( SELECT
						`b`.`ID`,
						`b`.`title`,
						`b`.`email`,
						`b`.`fax`,
						`b`.`phone`,
						`b`.`address`,
						'company' as `type`,
						`b`.`date_created`,
						`b`.`date_updated`,
						`b`.`created_by_id`
					FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id' 
						$where2
				)
				$order_by $limit");
		}		
			
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Contact?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
					
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
	
	public function viewcompanyAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts_companies` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				( 
					`a`.`created_by_id`='$user_id' 
					OR
					EXISTS( SELECT `e`.`contact_id` 
						FROM `contacts_users` as `e`
							WHERE `a`.`ID`=`e`.`contact_id` 
								AND `e`.`user_id`='$user_id' AND `e`.`type`='company')
				)
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
		
		if( !$post ){
			return $this->setContent(error('Liên hệ không tồn tại hoặc không có quyền xem'));
		}
		
		$labels	= $this->Model->fetchAll("SELECT `a`.* 
			FROM `contact_labels` as `a` 
			LEFT JOIN `contacts_contact_labels` as `b`
				ON `a`.`ID`=`b`.`label_id` 
					AND `b`.`contact_id`='$post_id'
					AND `b`.`type`='company'
			WHERE 
				`a`.`user_id`='{$post['created_by_id']}' 
				AND `b`.`type`='company'");
				
		$users = $this
			->Model->fetchAll("SELECT `a`.*
				FROM `users` as `a` 
				LEFT JOIN `contacts_users` as `b`
					ON `b`.`user_id`=`a`.`ID` 
						AND `b`.`contact_id`='$post_id' AND `b`.`type`='company' 
				WHERE `b`.`contact_id` IS NOT NULL");
		$this->set(array(
			labels	=> $labels,
			users	=> $users
		));

		
		$this->set(array(
			post => $post
		));	
	}
		
	public function uploadcompanyAction(){
		$this->removeLayout();		
		$user_id = get_user_id();		
		$post_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT * 
			FROM `contacts_companies` 
			WHERE 
				`ID`='$post_id'
				AND `created_by_id`='$user_id'");
			
		if( !$post ){
			return $this->setJSON(array(
				alert	=> 'Bản ghi đã bị xóa hoặc không tồn tại'
			));
		}

		if( $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert	=> 'Bạn không được phép tải tệp tin lên'
			));	
		}			
	
		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();

			$f->addField(array(
				img => array(
					type 		=> 'FILE',
					resize		=> array(110,110),
					path		=> 'files/contact/',
					no_empty	=> true,
					return_name	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					alert => $data
				));	
			}
			
			if( $post['img'] && ( $post['img'] != $data['img'] ) ){
				@unlink("files/contact/{$post['img']}");
			}
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				close	=> 'no',
				callback => "(function(){
					var link =baseURL+'/files/contact/{$data['img']}';
					$('#contact_img')
						.htm('<a href=\"'+link+'\" target=\"_blank\"><img src=\"'+link+'\"/></a>'
							+ '<a onclick=\"ajax_load(baseURL+\\'/Contact/Index/Deleteimgcompany?ID={$post['ID']}\\')\">[Xóa ảnh]</a>'
						)
				})()"
			));	
		}
		
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}

	public function addcompanyAction(){
		if( get('_iframe','no') == 'yes'){
			$this->removeLayout();
		}
		
		$user_id = get_user_id();		
		if( !isPost() ){
			$post = $this->Model->fetchRow("SELECT * 
				FROM `contacts_companies` 
				WHERE 
					`created_by_id`='$user_id' 
					AND `is_draft`='yes'
				LIMIT 1");

			if( $post ){
				$this->set('ID',$post['ID']);
			}else{
				$this->Model->insert('contacts_companies',array(
					is_draft		=> 'yes',
					created_by_id	=> $user_id
				));
				
				$this->set('ID',$this->Model->lastId());
			}		
		}			
		
		$labels = $this->Model->fetchAll("SELECT * FROM `contact_labels` WHERE `user_id`='$user_id'");
		$this->set(array(
			labels	=> $labels
		));
		
		if(isPost()){
			$post_id = getInt('ID',0);
			
			if( !$this->Model->fetchRow("SELECT * 
				FROM `contacts_companies` 
				WHERE 
					`created_by_id`='$user_id' 
				LIMIT 1") ){
					
				return $this->setJSON(array(
					alert	=> 'Bản đã bị xóa hoặc ghi không tồn tại'				
				));		
				
			}
			
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldCompany() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data['is_draft']='no';			
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = new Model_Expr('NOW()');
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");				

			//share			
			$users = get('users',array(),true);	
			$useradd = array();
			
			foreach( $users as $k => $uid ){
				if( $uid == $user_id OR !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
				}	
				
				if( $this->Model->fetchRow("SELECT * FROM `contacts_users` 
					WHERE `contact_id`='$post_id' AND `user_id`='$uid' AND `type`='company'") ){
						continue;
				}
				
				$this->Model->insert('contacts_users',array(
					contact_id	=> $post_id,	
					user_id		=> $uid,
					type		=> 'company'
				));
				
				$useradd[] ="'$uid'";
				
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $uid,
					url				=> "#Contact/Index/Viewcompany?ID=$post_id",
					title			=> $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> "Bạn được chia sẻ một liên hệ"
				));			
			}			
			
			$this->Model->delete('contacts_users'
				,"`contact_id`='$post_id' AND `type`='company' ". ( count($useradd) > 0 ? ' AND `user_id` NOT IN('.implode(',',$useradd).')' :'') );
			
			//label
			$labels = get('labels',array(),true);				
			
			$labeladd = array();
			foreach( $labels as $k => $lid ){
				if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
					WHERE `ID`='$lid' AND `user_id`='$user_id'") ){
						continue;
				}	

				if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
					WHERE `contact_id`='$post_id' AND `label_id`='$lid' AND `type`='company'") ){
						continue;
				}	
				
				$this->Model->insert('contacts_contact_labels',array(
					contact_id		=> $post_id,	
					label_id		=> $lid,
					type			=> 'company'
				));
				
				$labeladd[] = "'$lid'";
			}		
			
			$this->Model->delete('contacts_contact_labels'
				,"`contact_id`='$post_id' AND `type`='company'". ( count($labeladd) > 0 ? ' AND `label_id` NOT IN('.implode(',',$labeladd).')' :'') );
			
			
			if( get('_iframe','no') == 'yes'){
				$this->setJSON(array(
					close	=> true,
					callback	=> "(function(){   $('#option-contact-company').child(0).after('<option value=\"$post_id\" selected>{$data['title']}</option>') })()"
				));
			}else{
				$this->setJSON(array(
					redirect =>	'#Contact/Index/Viewcompany?ID='.$post_id
				));
			}	
		}		
	}

	public function editcompanyAction(){
		$user_id = get_user_id();		
		$post_id = getInt('ID',0);
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts_companies` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`created_by_id`='$user_id'				
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");

		if( !$post ){
			return $this->setContent(error('Bản ghi không tồn tại hoặc đã bị xóa'));
		}		
		
		$this->set('post',$post);

		$labels = $this->Model->fetchAll("SELECT *,
				IF( EXISTS(SELECT `b`.`contact_id` 
					FROM `contacts_contact_labels` as `b` 
					WHERE `b`.`contact_id`='$post_id' 
						AND `b`.`type`='company' 
						AND `b`.`label_id`=`a`.`ID`),' checked','') as `checked`  
			FROM `contact_labels` as `a`
			WHERE `a`.`user_id`='$user_id'");
			
		$users = $this
			->Model->fetchAll("SELECT `a`.*
				FROM `users` as `a` 
				LEFT JOIN `contacts_users` as `b`
					ON `b`.`user_id`=`a`.`ID` 
						AND `b`.`contact_id`='$post_id' AND `b`.`type`='company' 
				WHERE `b`.`contact_id` IS NOT NULL");
		$this->set(array(
			labels	=> $labels,
			users	=> $users
		));
		
		if(isPost()){		
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldCompany() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}			
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");				
	
			//share			
			$users = get('users',array(),true);	
			$useradd = array();
			
			foreach( $users as $k => $uid ){
				if( $uid == $user_id OR !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
				}	
				
				$useradd[] ="'$uid'";
				if( $this->Model->fetchRow("SELECT * FROM `contacts_users` 
					WHERE `contact_id`='$post_id' AND `user_id`='$uid' AND `type`='company'") ){
						continue;
				}
				
				$this->Model->insert('contacts_users',array(
					contact_id	=> $post_id,	
					user_id		=> $uid,
					type		=> 'company'
				));
								
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $uid,
					url				=> "#Contact/Index/Viewcompany?ID=$post_id",
					title			=> $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> "Bạn được chia sẻ một liên hệ"
				));			
			}			
			
			$this->Model->delete('contacts_users'
				,"`contact_id`='$post_id' AND `type`='company' ". ( count($useradd) > 0 ? ' AND `user_id` NOT IN('.implode(',',$useradd).')' :'') );
			
			//label
			$labels = get('labels',array(),true);				
			
			$labeladd = array();
			foreach( $labels as $k => $lid ){
				if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
					WHERE `ID`='$lid' AND `user_id`='$user_id'") ){
						continue;
				}	

				$labeladd[] = "'$lid'";
				if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
					WHERE `contact_id`='$post_id' AND `label_id`='$lid' AND `type`='company'") ){
						continue;
				}	
				
				$this->Model->insert('contacts_contact_labels',array(
					contact_id		=> $post_id,	
					label_id		=> $lid,
					type			=> 'company'
				));
			}		
			
			$this->Model->delete('contacts_contact_labels'
				,"`contact_id`='$post_id' AND `type`='company'". ( count($labeladd) > 0 ? ' AND `label_id` NOT IN('.implode(',',$labeladd).')' :'') );
	
			$this->setJSON(array(
				redirect =>	'#Contact/Index/Viewcompany?ID='.$post_id
			));
		}
	}	

	public function deleteimgcompanyAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*
			FROM `contacts_companies` as `a`
			WHERE 
				`a`.`created_by_id`='$user_id' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}
		
		$this->Model->update('contacts_companies',array(
			img	=> NULL
		),"ID='$post_id'");	
		
		return $this->setJSON(array(
			callback => "(function(){
				$('#contact_img').htm('')
			})()"
		));	
	}	
	
	public function viewpersonAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`,
				`d`.`title` as `company_title`					
			FROM `contacts` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			LEFT JOIN `contacts_companies` as `d`
				ON `a`.`company_id`=`d`.`ID`
			WHERE 
				( 
					`a`.`created_by_id`='$user_id' 
					OR
					EXISTS( SELECT `e`.`contact_id` 
						FROM `contacts_users` as `e`
							WHERE `a`.`ID`=`e`.`contact_id` 
								AND `e`.`user_id`='$user_id' AND `e`.`type`='person')
				)				
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
		
		if( !$post ){
			return $this->setContent(error('Liên hệ không tồn tại hoặc không có quyền xem'));
		}
		
		$labels	= $this->Model->fetchAll("SELECT `a`.* 
			FROM `contact_labels` as `a` 
			LEFT JOIN `contacts_contact_labels` as `b`
				ON `a`.`ID`=`b`.`label_id` 
					AND `b`.`contact_id`='$post_id'
					AND `b`.`type`='person'
			WHERE 
				`a`.`user_id`='{$post['created_by_id']}' 
				AND `b`.`type`='person'");

		$users = $this
			->Model->fetchAll("SELECT `a`.*
				FROM `users` as `a` 
				LEFT JOIN `contacts_users` as `b`
					ON `b`.`user_id`=`a`.`ID` 
						AND `b`.`contact_id`='$post_id' AND `b`.`type`='person' 
				WHERE `b`.`contact_id` IS NOT NULL");
				
		$this->set(array(
			post 	=> $post,
			labels	=> $labels,
			users	=> $users
		));	
	}
		
	public function uploadpersonAction(){
		$this->removeLayout();		
		$user_id = get_user_id();		
		$post_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT * 
			FROM `contacts` 
			WHERE 
				`ID`='$post_id'
				AND `created_by_id`='$user_id'");
			
		if( !$post ){
			return $this->setJSON(array(
				alert	=> 'Bản ghi đã bị xóa hoặc không tồn tại'
			));
		}

		if( $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert	=> 'Bạn không được phép tải tệp tin lên'
			));	
		}			
	
		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();

			$f->addField(array(
				img => array(
					type 		=> 'FILE',
					resize		=> array(110,110),
					path		=> 'files/contact/',
					no_empty	=> true,
					return_name	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					alert => $data
				));	
			}
			
			if( $post['img'] && ( $post['img'] != $data['img'] ) ){
				@unlink("files/contact/{$post['img']}");
			}
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				close	=> 'no',
				callback => "(function(){
					var link =baseURL+'/files/contact/{$data['img']}';
					$('#contact_img')
						.htm('<a href=\"'+link+'\" target=\"_blank\"><img src=\"'+link+'\"/></a>'
							+ '<a onclick=\"ajax_load(baseURL+\\'/Contact/Index/Deleteimgperson?ID={$post['ID']}\\')\">[Xóa ảnh]</a>'
						)
				})()"
			));	
		}
	}

	public function addpersonAction(){
		$user_id = get_user_id();	
		
		$companies = $this->Model->fetchAll("SELECT `a`.* FROM `contacts_companies` as `a` WHERE `a`.`is_draft`='no' AND `a`.`created_by_id`='$user_id'");
		$this->set('companies',$companies);
		
		if( !isPost() ){
			$post = $this->Model->fetchRow("SELECT * 
				FROM `contacts` 
				WHERE 
					`created_by_id`='$user_id' 
					AND `is_draft`='yes' 
				LIMIT 1");

			if( $post ){
				$this->set('ID',$post['ID']);
			}else{
				$this->Model->insert('contacts',array(
					is_draft		=> 'yes',
					created_by_id	=> $user_id
				));
				
				$this->set('ID',$this->Model->lastId());
			}		
		}			
		
		$labels = $this->Model->fetchAll("SELECT * FROM `contact_labels` WHERE `user_id`='$user_id'");
		$this->set(array(
			labels	=> $labels
		));
		
		if(isPost()){
			$post_id = getInt('ID',0);
			
			if( !$this->Model->fetchRow("SELECT * 
				FROM `contacts` 
				WHERE 
					`created_by_id`='$user_id'
				LIMIT 1") ){
					
				return $this->setJSON(array(
					alert	=> 'Bản đã bị xóa hoặc ghi không tồn tại'				
				));		
				
			}
			
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldPerson() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data['is_draft']='no';			
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = new Model_Expr('NOW()');
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");
						
			//share			
			$users = get('users',array(),true);	
			$useradd = array();
			
			foreach( $users as $k => $uid ){
				if( $uid == $user_id OR !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
				}	
				
				if( $this->Model->fetchRow("SELECT * FROM `contacts_users` 
					WHERE `contact_id`='$post_id' AND `user_id`='$uid' AND `type`='person'") ){
						continue;
				}
				
				$this->Model->insert('contacts_users',array(
					contact_id	=> $post_id,	
					user_id		=> $uid,
					type		=> 'person'
				));
				
				$useradd[] ="'$uid'";
				
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $uid,
					url				=> "#Contact/Index/Viewperson?ID=$post_id",
					title			=> $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> "Bạn được chia sẻ một liên hệ"
				));			
			}			
			
			$this->Model->delete('contacts_users'
				,"`contact_id`='$post_id' AND `type`='person' ". ( count($useradd) > 0 ? ' AND `user_id` NOT IN('.implode(',',$useradd).')' :'') );
			
			//label
			$labels = get('labels',array(),true);				
			
			$labeladd = array();
			foreach( $labels as $k => $lid ){
				if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
					WHERE `ID`='$lid' AND `user_id`='$user_id'") ){
						continue;
				}	

				if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
					WHERE `contact_id`='$post_id' AND `label_id`='$lid' AND `type`='person'") ){
						continue;
				}	
				
				$this->Model->insert('contacts_contact_labels',array(
					contact_id		=> $post_id,	
					label_id		=> $lid,
					type			=> 'person'
				));
				
				$labeladd[] = "'$lid'";
			}		
			
			$this->Model->delete('contacts_contact_labels'
				,"`contact_id`='$post_id' AND `type`='person'". ( count($labeladd) > 0 ? ' AND `label_id` NOT IN('.implode(',',$labeladd).')' :'') );
			
			
			$this->setJSON(array(
				redirect =>	'#Contact/Index/Viewperson?ID='.$post_id
			));
		}		
	}

	public function editpersonAction(){
		$user_id = get_user_id();		
		$post_id = getInt('ID',0);
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`created_by_id`='$user_id'				
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");

		if( !$post ){
			return $this->setContent(error('Bản ghi không tồn tại hoặc đã bị xóa'));
		}		
		
		$users = $this
			->Model->fetchAll("SELECT `a`.*
				FROM `users` as `a` 
				LEFT JOIN `contacts_users` as `b`
					ON `b`.`user_id`=`a`.`ID` 
						AND `b`.`contact_id`='$post_id' AND `b`.`type`='person' 
				WHERE `b`.`contact_id` IS NOT NULL");
				
		$labels = $this->Model->fetchAll("SELECT *,
				IF( EXISTS(SELECT `b`.`contact_id` 
					FROM `contacts_contact_labels` as `b` 
					WHERE `b`.`contact_id`='$post_id' 
						AND `b`.`type`='person' AND `b`.`label_id`=`a`.`ID`),' checked','') as `checked`  
			FROM `contact_labels` as `a`
			WHERE `a`.`user_id`='$user_id'");
		
		$this->set(array(
			labels	=> $labels,
			users	=> $users
		));		
		
		$this->set('post',$post);
		
		$companies = $this->Model->fetchAll("SELECT `a`.* FROM `contacts_companies` as `a` 
			WHERE `a`.`is_draft`='no' AND `a`.`created_by_id`='$user_id' ORDER BY `a`.`title`");
		$this->set('companies',$companies);
		
		if(isPost()){		
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldPerson() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}			
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");				
			
			
			//share			
			$users = get('users',array(),true);	
			$useradd = array();
			
			foreach( $users as $k => $uid ){
				if( $uid == $user_id OR !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
				}	
				
				$useradd[] ="'$uid'";				
				
				if( $this->Model->fetchRow("SELECT * FROM `contacts_users` 
					WHERE `contact_id`='$post_id' AND `user_id`='$uid' AND `type`='person'") ){
						continue;
				}
				
				$this->Model->insert('contacts_users',array(
					contact_id	=> $post_id,	
					user_id		=> $uid,
					type		=> 'person'	
				));
				
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $uid,
					url				=> "#Contact/Index/Viewperson?ID=$post_id",
					title			=> $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> "Bạn được chia sẻ một liên hệ"
				));			
			}			
			
			$this->Model->delete('contacts_users'
				,"`contact_id`='$post_id' AND `type`='person' ". ( count($useradd) > 0 ? ' AND `user_id` NOT IN('.implode(',',$useradd).')' :'') );
			
			//label
			$labels = get('labels',array(),true);				
			
			$labeladd = array();
			foreach( $labels as $k => $lid ){
				if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
					WHERE `ID`='$lid' AND `user_id`='$user_id'") ){
						continue;
				}	

				$labeladd[] = "'$lid'";	
				if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
					WHERE `contact_id`='$post_id' AND `label_id`='$lid' AND `type`='person'") ){
						continue;
				}	
				
				$this->Model->insert('contacts_contact_labels',array(
					contact_id		=> $post_id,	
					label_id		=> $lid,
					type			=> 'person'
				));
			}		
			
			$this->Model->delete('contacts_contact_labels'
				,"`contact_id`='$post_id' AND `type`='person'". ( count($labeladd) > 0 ? ' AND `label_id` NOT IN('.implode(',',$labeladd).')' :'') );
			
			
			$this->setJSON(array(
				redirect =>	'#Contact/Index/Viewperson?ID='.$post_id
			));
		}
	}	

	public function deleteimgpersonAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*
			FROM `contacts` as `a`
			WHERE 
				`a`.`created_by_id`='$user_id' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}
		$this->Model->update('contacts',array(
			img	=> NULL
		),"ID='$post_id'");	
		
		return $this->setJSON(array(
			callback => "(function(){
				$('#contact_img').htm('')
			})()"
		));	
	}	

	public function deleteAction(){
		$ids = get('personID',array(),true);
		$this->removeLayout();
		$user_id = get_user_id();
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");

			if( !$post ) continue;		 
			
			$this->Model->delete('contacts',"`ID`='$id'");
			$this->Model->delete('contacts_users',"`contact_id`='$id' AND `type`='person'");
			$this->Model->delete('contacts_contact_labels',"`contact_id`='$id' AND `type`='person'");
			
			if( $post['img'] ){
				@unlink("files/contact/{$post['img']}");
			}			
		}
		
		
		$ids = get('companyID',array(),true);
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts_companies` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");
			if( !$post ) continue;
			
			$this->Model->delete('contacts_companies',"`ID`='$id'");
			$this->Model->delete('contacts_users',"`contact_id`='$id' AND `type`='company'");
			$this->Model->delete('contacts_contact_labels',"`contact_id`='$id' AND `type`='company'");
			
			if( $post['img'] ){
				@unlink("files/contact/{$post['img']}");
			}			
		}		
	
		return $this->setJSON(array(
			redirect => get('url','#Contact')
		));
	}

	/* Label */
	private function fieldLabel(){
		return array(
			label	=> array(
				type	=> 'CHAR',
				no_empty	=> true,
				form_label	=> 'Tên nhãn'	
			),
			user_id	=> array(
				type			=> 'NONE',
				default_value	=>	get_user_id()
			)
		);
	}

	public function showlabelAction(){
		$user_id = get_user_id();
		$labels = $this->Model->fetchAll("SELECT * FROM `contact_labels` WHERE `user_id`='$user_id'");
		$this->set(array(
			labels	=> $labels
		));
	}
	
	public function labelAction(){
		$this->removeLayout();
		$user_id = get_user_id();
		if(isPost()){
			$act = get('act','');
			if( $act == 'add'){
				loadClass('ZData');
				$form = new ZData();
				$form->addFields( $this->fieldLabel() );
				$data = $form->getData();			
			
				if( !is_array( $data )){
					$this->set(array(
						message => $data
					));			
				}else{			
					$this->Model->insert('contact_labels',$data);
				}	
			}else if( $act == 'edit' ){
				$label_id = get('ID');
				$label = $this->Model->fetchRow("SELECT * 
					FROM `contact_labels` WHERE `ID`='$label_id' AND `user_id`='$user_id'");
				if( $label ){
					loadClass('ZData');
					$form = new ZData();
					$form->addFields( $this->fieldLabel() );
					$data = $form->getData();			
				
					if( !is_array( $data )){
						$this->set(array(
							message => $data
						));			
					}else{			
						$this->Model->update('contact_labels',$data,"`ID`='$label_id'");
					}				
				}			
			}else if( $act == 'delete' ){
				$label_id = get('ID');	
				$label = $this->Model->fetchRow("SELECT * 
					FROM `contact_labels` WHERE `ID`='$label_id' AND `user_id`='$user_id'");
				if( $label ){	
					$this->Model->delete('contact_labels',"`ID`='$label_id'");
					$this->Model->delete('contacts_contact_labels',"`label_id`='$label_id'");					
				}	
			}
		}
			
		$labels = $this->Model->fetchAll("SELECT * FROM `contact_labels` WHERE `user_id`='$user_id'");
		$this->set(array(
			labels	=> $labels
		));	
	}	
	
	/* search */
	public function searchAction(){
		$word = get('s','');
		
		if(empty($word)){
			return $this->setJSON(array(
				alert	=> 'Chưa có từ khóa tìm kiếm'				
			));			
		}
	
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `date_created` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','email','fax','phone','address','mobile');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$where=array();
		$where1=array();
		foreach( array('title','address','address2','phone','email') as $f ){
			$where[] = "`a`.`$f` LIKE '%$word%'";		
			$where1[] = "`b`.`$f` LIKE '%$word%'";		
		}
		
		$where = implode('OR',$where);	
		$where1 = implode('OR',$where1);	
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) FROM ( ( SELECT	
					`a`.`ID`
				FROM  `contacts` as `a`
				WHERE
					`a`.`is_draft`='no'
					AND `a`.`created_by_id`='$user_id'
					AND ( $where )
			) UNION 
			( SELECT
					`b`.`ID`
				FROM  `contacts_companies` as `b`
				WHERE
					`b`.`is_draft`='no'
					AND `b`.`created_by_id`='$user_id'
					AND ( $where1 )
			)) as `k`
		");
				
		$posts = $this->Model->fetchAll(" 
			( SELECT	
					`a`.`ID`,
					`a`.`title`,
					`a`.`email`,
					`a`.`fax`,
					`a`.`phone`,
					`a`.`address`,
					'person' as `type`,
					`a`.`date_created`,
					`a`.`date_updated`,
					`a`.`created_by_id`
				FROM  `contacts` as `a`
				WHERE
					`a`.`is_draft`='no'
					AND `a`.`created_by_id`='$user_id'
					AND ( $where )
			) UNION 
			( SELECT
					`b`.`ID`,
					`b`.`title`,
					`b`.`email`,
					`b`.`fax`,
					`b`.`phone`,
					`b`.`address`,
					'company' as `type`,
					`b`.`date_created`,
					`b`.`date_updated`,
					`b`.`created_by_id`
				FROM  `contacts_companies` as `b`
				WHERE
					`b`.`is_draft`='no'
					AND `b`.`created_by_id`='$user_id'
					AND ( $where1 )
			)		
			$order_by $limit");
			
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Contact?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
					
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}

	/* shared */
	public function shareAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `date_created` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','email','fax','phone','address','mobile');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$word = get('s','');
		if( $word ){
			$where1=array();
			$where2=array();
			foreach( array('title','address','address2','phone','email') as $f ){
				$where1[] = "`a`.`$f` LIKE '%$word%'";		
				$where2[] = "`b`.`$f` LIKE '%$word%'";		
			}
			
			$where1 = ' AND ('.implode('OR',$where1).')';	
			$where2 = ' AND ('.implode('OR',$where2).')';
		}
		
		$type = get('type','all');
		
		if(  $type == 'person' ){
		
			$vars['type'] = 'person';
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
				FROM  `contacts` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id'
			");
					
			$posts = $this->Model->fetchAll("SELECT	
					`a`.`ID`,
					`a`.`title`,
					`a`.`email`,
					`a`.`fax`,
					`a`.`phone`,
					`a`.`address`,
					'person' as `type`,
					`a`.`date_created`,
					`a`.`date_updated`,
					`a`.`created_by_id`
				FROM  `contacts` as `a`
				WHERE
					`a`.`is_draft`='no'
					AND EXISTS( SELECT `c`.`contact_id` 
						FROM `contacts_users` as `c`
							WHERE `a`.`ID`=`c`.`contact_id` 
								AND `c`.`user_id`='$user_id' AND `c`.`type`='person')
					$where1			
			$order_by $limit");		
			
		}else if( $type == 'company'){
			$vars['type'] = 'company';
		
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
				FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND `b`.`created_by_id`='$user_id'");
					
			$posts = $this->Model->fetchAll("SELECT	
					`a`.`ID`,
					`a`.`title`,
					`a`.`email`,
					`a`.`fax`,
					`a`.`phone`,
					`a`.`address`,
					'company' as `type`,
					`a`.`date_created`,
					`a`.`date_updated`,
					`a`.`created_by_id`
				FROM  `contacts_companies` as `a`
				WHERE
					`a`.`is_draft`='no'
					AND EXISTS( SELECT `c`.`contact_id` 
						FROM `contacts_users` as `c`
							WHERE `a`.`ID`=`c`.`contact_id` 
								AND `c`.`user_id`='$user_id' AND `c`.`type`='company')
					$where1			
			$order_by $limit");
			
		}else{
			$total = $this->Model->fetchOne("SELECT COUNT(*) FROM ( ( SELECT	
						`a`.`ID`
					FROM  `contacts` as `a`
					WHERE
						`a`.`is_draft`='no'
						AND EXISTS( SELECT `c`.`contact_id` 
						FROM `contacts_users` as `c`
							WHERE `a`.`ID`=`c`.`contact_id` 
								AND `c`.`user_id`='$user_id' AND `c`.`type`='person'
						)
						$where1	
				) UNION 
				( SELECT
						`b`.`ID`
					FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND EXISTS( SELECT `d`.`contact_id` 
							FROM `contacts_users` as `d`
								WHERE `b`.`ID`=`d`.`contact_id` 
									AND `d`.`user_id`='$user_id' AND `d`.`type`='company'
							)
						$where2	
				)) as `k`
			");
					
			$posts = $this->Model->fetchAll(" 
				( SELECT	
						`a`.`ID`,
						`a`.`title`,
						`a`.`email`,
						`a`.`fax`,
						`a`.`phone`,
						`a`.`address`,
						'person' as `type`,
						`a`.`date_created`,
						`a`.`date_updated`,
						`a`.`created_by_id`
					FROM  `contacts` as `a`
					WHERE
						`a`.`is_draft`='no'
						AND EXISTS( SELECT `d`.`contact_id` 
							FROM `contacts_users` as `d`
								WHERE `a`.`ID`=`d`.`contact_id` 
									AND `d`.`user_id`='$user_id' AND `d`.`type`='person')
						$where1			
				) UNION 
				( SELECT
						`b`.`ID`,
						`b`.`title`,
						`b`.`email`,
						`b`.`fax`,
						`b`.`phone`,
						`b`.`address`,
						'company' as `type`,
						`b`.`date_created`,
						`b`.`date_updated`,
						`b`.`created_by_id`
					FROM  `contacts_companies` as `b`
					WHERE
						`b`.`is_draft`='no'
						AND EXISTS( SELECT `c`.`contact_id` 
							FROM `contacts_users` as `c`
								WHERE `b`.`ID`=`c`.`contact_id` 
									AND `c`.`user_id`='$user_id' AND `c`.`type`='company')
						$where2
				)
				$order_by $limit");
		}		
			
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Contact/Share?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
					
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
	
	public function addlabelAction(){
		$label_id = get('label_id',0);
		$user_id = get_user_id();
		$this->removeLayout();
		if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
			WHERE `ID`='$label_id' AND `user_id`='$user_id'") ){
				return $this->setJSON(array(
					message	=> 'Nhãn không tồn tại hoặc đã bị xóa'
				));
		}	
	
		$ids = get('personID',array(),true);
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");

			if( !$post ) continue;		 

			if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
				WHERE `contact_id`='$id' AND `label_id`='$label_id' AND `type`='person'") ){
					continue;
			}	
			
			$this->Model->insert('contacts_contact_labels',array(
				contact_id		=> $id,	
				label_id		=> $label_id,
				type			=> 'person'
			));
		}
		
		
		$ids = get('companyID',array(),true);
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts_companies` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");

			if( !$post ) continue;		 

			if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
				WHERE `contact_id`='$id' AND `label_id`='$label_id' AND `type`='company'") ){
					continue;
			}	
			
			$this->Model->insert('contacts_contact_labels',array(
				contact_id		=> $id,	
				label_id		=> $label_id,
				type			=> 'company'
			));			
		}		
	
		return $this->setJSON(array(
			message => 'Đã gán nhãn thành công'
		));
	}

	public function movelabelAction(){
		$label_id = get('label_id',0);
		$user_id = get_user_id();
		$this->removeLayout();
		if( !$this->Model->fetchRow("SELECT * FROM `contact_labels` 
			WHERE `ID`='$label_id' AND `user_id`='$user_id'") ){
				return $this->setJSON(array(
					message	=> 'Nhãn không tồn tại hoặc đã bị xóa'
				));
		}	
	
		$ids = get('personID',array(),true);
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");

			if( !$post ) continue;		 

			$this->Model->delete('contacts_contact_labels',"`type`='person' AND `contact_id`='$id' AND `label_id`<>'$label_id'");
			if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
				WHERE `contact_id`='$id' AND `label_id`='$label_id' AND `type`='person'") ){
					continue;
			}	
			
			$this->Model->insert('contacts_contact_labels',array(
				contact_id		=> $id,	
				label_id		=> $label_id,
				type			=> 'person'
			));
		}
		
		
		$ids = get('companyID',array(),true);
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts_companies` as `a`
				WHERE 
					`a`.`created_by_id`='$user_id' 
					AND `a`.`ID`='$id'
					AND `a`.`is_draft`='no'
				LIMIT 1");

			if( !$post ) continue;		 

			$this->Model->delete('contacts_contact_labels',"`type`='company' AND `contact_id`='$id' AND `label_id`<>'$label_id'");
			
			if( $this->Model->fetchRow("SELECT * FROM `contacts_contact_labels` 
				WHERE `contact_id`='$id' AND `label_id`='$label_id' AND `type`='company'") ){
					continue;
			}	
			
			
			$this->Model->insert('contacts_contact_labels',array(
				contact_id		=> $id,	
				label_id		=> $label_id,
				type			=> 'company'
			));			
		}		
	
		return $this->setJSON(array(
			message => 'Đã di chuyển nhãn thành công'
		));
	}

		
	
}	